const getOuterTrade = require('../utils/outTradeNo')
const { submitOrderService } = require('../service/payment.service')
const alipaySdk = require('../utils/alipayUtil')
const AlipayFormData = require('alipay-sdk/lib/form').default
const axios = require('axios')
class PaymentController {
  async submitOrder(ctx, next) {
    const orderId = getOuterTrade()
    const res = await submitOrderService(ctx.request.body.order, orderId)
    if (res.length !== 0) {
      ctx.body = {
        status: 200,
        masg: 'ok',
        orderId,
        data: res
      }
    }
  }
  async payOrder(ctx, next) {
    const titles = []
    const { orderId } = ctx.request.body.order
    const goodsData = ctx.request.body.order.goodsData
    goodsData.forEach(item => {
      titles.push(item.title)
    })
    const title = titles.toString()
    const totalPrice = goodsData.reduce((prev, item, index) => prev + item.price * item.count, 0)
    // 调用支付宝sdk
    const formData = new AlipayFormData();
    formData.setMethod('get');
    formData.addField('bizContent', {
      outTradeNo: orderId, // 商户订单号,64个字符以内、可包含字母、数字、下划线,且不能重复
      productCode: 'FAST_INSTANT_TRADE_PAY', // 销售产品码，与支付宝签约的产品码名称,仅支持FAST_INSTANT_TRADE_PAY
      totalAmount: totalPrice, // 订单总金额，单位为元，精确到小数点后两位
      subject: title, // 订单标题
    });
    formData.addField('returnUrl', 'http://localhost:8080/order/paysuccess');//加在这里才有效果,不是加在bizContent 里面
    const result = await alipaySdk.exec(  // result 为可以跳转到支付链接的 url
      'alipay.trade.wap.pay', // 统一收单下单并支付页面接口
      {}, // api 请求的参数（包含“公共请求参数”和“业务参数”）
      { formData: formData },
    );
    await next()
    ctx.body = {
      status: 200,
      mas: 'ok',
      result
    }
  }
  async queryPayResult(ctx, next) {
    const { out_trade_no, trade_no } = ctx.request.body
    const formData = new AlipayFormData();
    formData.setMethod('get');
    formData.addField('bizContent', {
      out_trade_no,
      trade_no
    });
    // 通过该接口主动查询订单状态
    const result = await alipaySdk.exec(
      'alipay.trade.query',
      {},
      { formData: formData },
    );
    const resp = await axios({
      method: 'GET',
      url: result
    })
    ctx.state = resp.data.alipay_trade_query_response
    await next()
  }
}

module.exports = new PaymentController()